<template>
  <div class="map-container-wrapper">
    <div ref="mapContainer" class="map-view-core" style="height: 100%; width: 100%;"></div>

    <div v-show="navigationPanelVisible" id="navigation-panel" class="navigation-panel"></div>

    <div class="map-controls">
      <el-input v-model="searchParams.name" placeholder="小区名称" clearable />
      <el-input v-model="searchParams.district" placeholder="行政区" clearable />
      <el-input v-model="searchParams.sub_district" placeholder="商圈" clearable />
      <el-input-number
        v-model="searchParams.price_min"
        placeholder="最低单价 (万元/㎡)"
        :min="0"
        :precision="2"
        style="width: 150px;"
      />
      <el-input-number
        v-model="searchParams.price_max"
        placeholder="最高单价 (万元/㎡)"
        :min="0"
        :precision="2"
        style="width: 150px;"
      />
      <div class="button-group-container">
        <el-button-group>
          <el-button type="primary" @click="handleSearch('text')">搜索</el-button>
          <el-button @click="enableRectangle">拉框范围</el-button>
          <el-button @click="enablePointSelection">点选半径</el-button>
          <el-button type="warning" @click="resetSearch">重置搜索</el-button>
           <el-button
            v-if="authStore.isAuthenticated"
            :type="isShowingFavorites ? 'info' : 'success'"
            @click="toggleShowFavorites"
            >
              {{ isShowingFavorites ? '隐藏收藏' : '显示收藏' }}
            </el-button>
           <el-button v-show="navigationPanelVisible" type="danger" @click="clearNavigation">清除导航</el-button>
        </el-button-group>

        <HeatmapComponent v-if="mapInstance" :map-instance="mapInstance" />
      </div>

      <el-input-number
        v-if="radiusVisible" v-model="searchParams.radius"
        :min="500"
        :max="100000"
        placeholder="半径（米）"
      />

      <el-select v-model="sortConfig.sortBy" placeholder="排序方式" @change="handleSortChange" style="width: 150px;">
      <el-option label="默认排序" value="id_asc"></el-option>
      <el-option label="均分从高到低" value="avg_rating_desc"></el-option>
      <el-option label="均分从低到高" value="avg_rating_asc"></el-option>
      </el-select>

      <el-checkbox
        v-if="authStore.isAuthenticated && authStore.getApiKey"
        v-model="useApiKeyForSearch"
        label="使用API Key查询"
        size="small"
        style="margin-left: 10px; color: #606266;"
      />
      <el-button
        v-if="propertyStore.hasMore && !propertyStore.loading && propertyStore.propertyList.length > 0"
        type="success"
        @click="loadMoreProperties"
        style="margin-left: 10px;"
      >
        显示更多 ({{ propertyStore.propertyList.length }} / {{ propertyStore.totalItems }})
      </el-button>
    </div>

    <el-alert v-if="propertyStore?.loading" title="正在加载房产数据..." type="info" show-icon :closable="false" class="map-feedback-alert" />
    <el-alert v-if="propertyStore?.error" :title="'加载错误: ' + propertyStore.error" type="error" show-icon class="map-feedback-alert" />

    <div class="bottom-right-button">
      <el-button type="danger" @click="handleExit" v-if="!authStore.isAuthenticated">退出</el-button>
    </div>
        <ReviewListModal
      v-if="selectedPropertyForReviews"
      :property-id="selectedPropertyForReviews.id"
      :property-name="selectedPropertyForReviews.name"
      v-model:visible="isReviewModalVisible"
    />
  </div>
</template>

<script setup>
import { onMounted, ref, shallowRef, onUnmounted, watch , nextTick} from 'vue';
import { UserFilled } from '@element-plus/icons-vue';
import { useAuthStore } from '@/stores/auth';
import { reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
// 修改: 确保只引入了 usePropertyStore
import { usePropertyStore } from '@/stores/properties.js';

import { useFootprintStore } from '@/stores/footprints.js';
import { debounce } from 'lodash';
import router from '@/router/index.js';
import HeatmapComponent from './HeatmapComponent.vue';
import ReviewListModal from "@/views/ReviewListModal.vue";

const CONFIG = {
  BATCH_SIZE: 20,
  RETRY_LIMIT: 3,
  DELAY_BETWEEN_BATCHES: 1000,
  DELAY_BETWEEN_RETRIES: 1000
};

const mapContainer = ref(null);
const mapInstance = ref(null);
const authStore = useAuthStore();
// 修改: 移除 poiStore, 只使用 propertyStore
const propertyStore = usePropertyStore();
// --- 【新增】: 实例化 footprint store ---
const footprintStore = useFootprintStore();
let driving = null; // 【新增】用于存储导航实例
const loading = ref(true);
const useApiKeyForSearch = ref(false);
const radiusVisible = ref(false);
const markers = shallowRef([]);
const poiMarkers = shallowRef([]);
const facilityCircles = shallowRef([]);

// 使用高德地图标准图标，统一风格
const facilityIconMap = {
  '医院': 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b1.png',
  '公园': 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b2.png',
  '大型商城': 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b3.png',
  '菜市场': 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b4.png',
  '地铁站': 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b5.png',
  '火车站': 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b6.png',
  '机场': 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b7.png',
  '学校': 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b8.png',
  'default': 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png'
};

function getFacilityIcon(type) {
  return facilityIconMap[type] || facilityIconMap['default'];
}

const pageSize = CONFIG.BATCH_SIZE;
let currentPage = 1;
const isDrawing = ref(false);
const currentDrawType = ref(null);
let currentOverlay = null;
let startPoint = null;
const currentCircle = shallowRef(null);
// 修改: searchParams 的字段与 property API 对齐
const searchParams = reactive({
  name: '',
  district: '',
  sub_district: '',
  radius: 1000 // 默认查询范围设为1000米
});
const clickModeActive = ref(false);
// --- 【修复问题1】新增一个状态，用于存储上一次执行搜索的完整参数 ---
const lastQueryParams = ref({});
// --- 用于控制评论对话框的状态 ---
const isReviewModalVisible = ref(false);
const selectedPropertyForReviews = ref(null);
// 1. 添加一个状态来存储当前的排序选择
const sortConfig = reactive({
  sortBy: 'id_asc', // 默认值
});
// 新增: 用于控制“显示收藏”模式的状态
const isShowingFavorites = ref(false);
const navigationPanelVisible = ref(false);


//////////////////////////////////////////////////////////////////////////////////////


// 【完整替换此函数】
const startNavigation = (endCoords) => {
  clearNavigation(); // 开始新导航前，先清除旧的
  const AMap = window.AMap;
  if (!AMap || !AMap.Driving) {
    ElMessage.error('导航插件未加载！');
    return;
  }

  ElMessage.info('正在获取您的当前位置...');
  const geolocation = new AMap.Geolocation({
    enableHighAccuracy: true,
    timeout: 10000,
  });

  geolocation.getCurrentPosition((status, result) => {
    if (status === 'complete') {
      const startPoint = result.position;
      const endPoint = new AMap.LngLat(endCoords[0], endCoords[1]);
      ElMessage.success('位置获取成功，开始规划路线！');

      if (!driving) {
        driving = new AMap.Driving({
          map: mapInstance.value,
          policy: AMap.DrivingPolicy.LEAST_TIME,
          // 将导航结果的详情渲染到指定 ID 的 div 中
          panel: 'navigation-panel'
        });
      }

      driving.search(startPoint, endPoint, (searchStatus, searchResult) => {
        if (searchStatus === 'complete' && searchResult.routes && searchResult.routes.length) {
          ElMessage.success('路线规划成功！');
          // 规划成功后，显示导航详情面板
          navigationPanelVisible.value = true;
        } else {
          ElMessage.error(`路线规划失败: ${searchResult.info || '未知错误'}`);
          navigationPanelVisible.value = false;
        }
      });

    } else {
      ElMessage.error('获取当前位置失败，请检查浏览器定位权限。');
      console.error('Geolocation error:', result);
    }
  });
};

const clearNavigation = () => {
  if (driving) {
    driving.clear(); // 清除地图上的路线
    navigationPanelVisible.value = false; // 隐藏导航详情面板
  }
};
// 新增: 切换收藏显示模式的函数
const toggleShowFavorites = () => {
  if (footprintStore.footprints.length === 0) {
      ElMessage.info('您还没有任何收藏记录。');
      return;
  }
  isShowingFavorites.value = !isShowingFavorites.value;
};

// 开发环境模拟模式配置
const MOCK_MODE = import.meta.env.MODE === 'development';
const AMAP_SECURITY_CONFIG = {
  securityJsCode: '5925c6e1bb0cc5d88d379ff29ad85a94'
};

const handleSortChange = () => {
  performSearch(lastQueryParams.value);
};

// --- 打开评论对话框的函数 ---
const openReviewModal = (property) => {
  isReviewModalVisible.value = false;
  selectedPropertyForReviews.value = property;

  nextTick(() => {
    isReviewModalVisible.value = true;
  });
};


// --- 【新增】: 处理收藏/取消收藏的函数 ---
const handleFavoriteClick = async (property) => {
  if (!authStore.isAuthenticated) {
    ElMessage.warning('请先登录后再进行收藏操作！');
    return;
  }
  const propertyId = property.id;
  const favBtn = document.getElementById(`fav-btn-${propertyId}`);
  if (!favBtn) return;

  // 防止重复点击
  favBtn.disabled = true;

  try {
    const isFavorited = footprintStore.isPropertyFootprinted(propertyId);
    if (isFavorited) {
      await footprintStore.removeFootprint(propertyId);
    } else {
      await footprintStore.addFootprint(propertyId);
    }
    // 操作成功后，更新按钮状态
    const isNowFavorited = footprintStore.isPropertyFootprinted(propertyId);
    favBtn.innerHTML = isNowFavorited ? '❤️&nbsp;已收藏' : '🤍&nbsp;收藏';
    favBtn.style.color = isNowFavorited ? '#ff4d4f' : '#606266';

  } catch (error) {
    // API调用失败时，消息已在store中提示
    console.error('收藏操作失败', error);
  } finally {
    // 恢复按钮
    favBtn.disabled = false;
  }
};

// --- 【新增】: 搜索周边生活服务设施的函数 ---
const searchNearbyFacilities = (property) => {
  clearPoiMarkers(); // 在进行新的搜索前，先清除旧的标记点
  const AMap = window.AMap;
  if (!AMap || !mapInstance.value) {
    ElMessage.error('地图实例尚未准备好');
    return;
  }

  ElMessage.info('正在搜索周边设施...');

  const placeSearch = new AMap.PlaceSearch({
    pageSize: 50, // 返回数量
    pageIndex: 1, // 页码
    city: '武汉', // 城市限制
    panel: 'navigation-panel', // 【复用】将结果列表显示在导航面板中
    autoFitView: false // 建议添加，阻止地图自动缩放，由我们自己控制
  });

  // 定义要搜索的设施类别
  const facilityKeywords = ['医院', '地铁站', '公园', '大型商城', '菜市场', '学校'];
  const searchCenter = property.coordinates; // 使用房产的坐标作为中心点

  placeSearch.searchNearBy(facilityKeywords.join('|'), searchCenter, 1000, (status, result) => {
    if (status === 'complete' && result.poiList && result.poiList.pois.length > 0) {
      ElMessage.success(`成功找到 ${result.poiList.pois.length} 个周边设施`);
      navigationPanelVisible.value = true; // 显示结果面板

      // searchNearBy 会自动添加标记，我们只需要将它们收集起来以便后续清除
      // 但为了自定义图标和信息窗，我们手动创建

      const newPoiMarkers = result.poiList.pois.map(poi => {
        const icon = getFacilityIcon(poi.type.split(';')[0]); // 使用已有的图标映射
        const marker = new AMap.Marker({
          position: poi.location,
          map: mapInstance.value,
          icon: new AMap.Icon({
              size: new AMap.Size(25, 34),
              image: icon,
              imageSize: new AMap.Size(25, 34)
          }),
          title: poi.name,
          zIndex: 90 // 让设施标记在房产标记之下
        });

        // 为每个设施标记也添加一个简单的信息窗
        marker.on('click', () => {
            const infoWindow = new AMap.InfoWindow({
                content: `
                    <div style="font-size: 12px; padding: 5px;">
                        <strong>${poi.name}</strong><br/>
                        地址: ${poi.address || 'N/A'}<br/>
                        类型: ${poi.type || 'N/A'}
                    </div>
                `,
                offset: new AMap.Pixel(0, -25)
            });
            infoWindow.open(mapInstance.value, poi.location);
        });
        return marker;
      });
      poiMarkers.value = newPoiMarkers; // 保存这些标记以便清除


    } else if (status === 'no_data') {
      ElMessage.warning('附近1公里内未找到相关生活设施');
      navigationPanelVisible.value = false;
    } else {
      ElMessage.error('周边设施搜索失败: ' + result);
      navigationPanelVisible.value = false;
    }
  });
};

// 在 handleFavoriteClick 函数后面添加这个新函数
const createPropertyMarker = (prop, useFavoriteIcon = false) => {
  const AMap = window.AMap;
  if (!prop.coordinates || prop.coordinates.length !== 2) return null;

  // 根据是否是收藏点，选择不同的图标
  const icon = useFavoriteIcon ? new AMap.Icon({
      size: new AMap.Size(25, 34),
      image: '/icon/star.png',
      imageSize: new AMap.Size(25, 25),
  }) : new AMap.Icon(
      {
      size: new AMap.Size(30, 30),
      image: '/icon/house.png',
      imageSize: new AMap.Size(30, 30),
      }
  ); // undefined 会使用高德地图默认图标

  const marker = new AMap.Marker({
    position: prop.coordinates,
    map: mapInstance.value,
    title: prop.name,
    icon: icon,
    zIndex: useFavoriteIcon ? 110 : 100, // 让收藏点标记在更上层
  });

  marker.on('click', () => {
    const isFavorited = footprintStore.isPropertyFootprinted(prop.id);
    const searchUrl = `https://www.baidu.com/s?wd=${encodeURIComponent(prop.name)}`;
    const favoriteButtonId = `fav-btn-${prop.id}`;
    const reviewButtonId = `review-btn-${prop.id}`;
    const nearbyButtonId = `nearby-btn-${prop.id}`;

    const infoWindow = new AMap.InfoWindow({
      content: `
        <div class="custom-info-window">
          <h3 style="margin: 0 0 8px; color: ${useFavoriteIcon ? '#ff4d4f' : '#1890ff'};">${prop.name} ${useFavoriteIcon ? '⭐' : ''}</h3>
          <table style="width:100%; font-size:12px; border-collapse: collapse;">
            <tr><td style="padding:4px; color: #666;">行政区</td><td style="padding:4px;">${prop.district || 'N/A'}</td></tr>
            <tr><td style="padding:4px; color: #666;">商圈</td><td style="padding:4px;">${prop.sub_district || 'N/A'}</td></tr>
            <tr><td style="padding:4px; color: #666;">均价</td><td style="padding:4px;">${prop.avg_unit_price ? prop.avg_unit_price.toFixed(2) + ' 万元/㎡' : 'N/A'}</td></tr>
            <tr><td style="padding:4px; color: #666;">平均总价</td><td style="padding:4px;">${prop.avg_total_price ? prop.avg_total_price.toFixed(2) + ' 万元' : 'N/A'}</td></tr>
            <tr><td style="padding:4px; color: #666;">最高总价</td><td style="padding:4px;">${prop.max_total_price ? prop.max_total_price.toFixed(2) + ' 万元' : 'N/A'}</td></tr>
            <tr><td style="padding:4px; color: #666;">最低总价</td><td style="padding:4px;">${prop.min_total_price ? prop.min_total_price.toFixed(2) + ' 万元' : 'N/A'}</td></tr>
            <p style="font-size:12px; margin: 4px 0;">
            <b>均分:</b>
            ${prop.avg_rating ? `<strong>${prop.avg_rating.toFixed(1)}</strong> 分` : '暂无评分'}
            </p>
            <tr>
              <td colspan="2" style="padding-top: 10px; display: flex; justify-content: space-between; align-items: center;">
                <a href="${searchUrl}" target="_blank" style="color: #409EFF; text-decoration: none;">🔍 查看详细信息</a>
                ${authStore.isAuthenticated ? `
                <button id="${favoriteButtonId}" style="
                  background: none;
                  border: 1px solid #dcdfe6;
                  padding: 4px 8px;
                  border-radius: 4px;
                  cursor: pointer;
                  color: ${isFavorited ? '#ff4d4f' : '#606266'};
                  display: flex;
                  align-items: center;
                  gap: 4px;
                  font-size: 12px;
                ">
                  ${isFavorited ? '❤️&nbsp;已收藏' : '🤍&nbsp;收藏'}
                </button>` : ''}
                <button id="${reviewButtonId}" style="background: none; border: 1px solid #409eff; color: #409eff; padding: 4px 8px; border-radius: 4px; cursor: pointer; font-size: 12px;">查看评论</button>
                <button id="nav-btn-${prop.id}" style="background: #67c23a; border: none; color: white; padding: 4px 8px; border-radius: 4px; cursor: pointer; font-size: 12px;">导航到这里</button>
                <button id="${nearbyButtonId}" style="background: #E6A23C; border: none; color: white; padding: 4px 8px; border-radius: 4px; cursor: pointer; font-size: 12px;">查看周边</button>
              </td>
            </tr>
          </table>
        </div>
      `,
      offset: new AMap.Pixel(0, -30)
    });

    infoWindow.on('open', () => {

      const reviewBtn = document.getElementById(reviewButtonId);
      if (reviewBtn) {
        reviewBtn.onclick = () => openReviewModal(prop);
      }
      if (authStore.isAuthenticated) {
        const favBtn = document.getElementById(favoriteButtonId);
        if (favBtn) {
          favBtn.onclick = () => handleFavoriteClick(prop);
        }
      }

      const navBtn = document.getElementById(`nav-btn-${prop.id}`);
      if (navBtn) {
        navBtn.onclick = () => startNavigation(prop.coordinates);
      }

      const nearbyBtn = document.getElementById(nearbyButtonId);
      if (nearbyBtn) {
        nearbyBtn.onclick = () => searchNearbyFacilities(prop);
      }
    });

    infoWindow.open(mapInstance.value, prop.coordinates);
  });

  return marker;
};


watch(isShowingFavorites, (isShowing) => {
  clearMarkers(); // 无论开启还是关闭，都先清空地图

  let propertiesToDisplay = [];
  let useFavoriteIcon = false;

  if (isShowing) {
    // 【模式一：显示收藏】
    ElMessage.success(`已切换为收藏视图。`);

    // --- 新增逻辑：创建一个包含完整房产信息的Map，用于快速查找 ---
    const fullPropertiesMap = new Map(
      (propertyStore.propertyList || []).map(p => [p.id, p])
    );

    propertiesToDisplay = footprintStore.footprints
      .map(fp => {
        const footprintProperty = fp.property;
        if (!footprintProperty) return null;

        // --- 核心修改 ---
        // 优先从完整的房产列表（Map）中获取数据
        // 如果找不到，再使用收藏信息中自带的（可能不完整的）数据
        return fullPropertiesMap.get(footprintProperty.id) || footprintProperty;
      })
      .filter(p => p && p.coordinates);

    useFavoriteIcon = true;
  } else {
    // 【模式二：显示常规搜索结果】
    ElMessage.info('已恢复为常规搜索视图。');
    propertiesToDisplay = propertyStore.propertyList || [];
    useFavoriteIcon = false;
  }

  const newMarkers = propertiesToDisplay
    .map(prop => createPropertyMarker(prop, useFavoriteIcon)) // <-- 核心改动：统一调用新函数
    .filter(marker => marker !== null);

  markers.value = newMarkers;

  if (newMarkers.length > 0) {
    mapInstance.value.setFitView();
  }
});


watch(() => propertyStore.propertyList, (newPropertyList) => {
  if (isShowingFavorites.value) {
    return; // 如果正在显示收藏，则不处理普通列表的变化，避免冲突
  }

  clearMarkers();
  const AMap = window.AMap;
  if (!AMap || !mapInstance.value) return;

  const currentMarkers = (newPropertyList || [])
    .map(prop => createPropertyMarker(prop, false)) // <-- 核心改动：统一调用新函数
    .filter(marker => marker !== null);

  markers.value = currentMarkers;

  if (currentMarkers.length > 0) {
    mapInstance.value.setFitView(currentMarkers, false, [150, 60, 100, 60]);
  }
}, { deep: true });

onMounted(async () => {
  window._AMapSecurityConfig = AMAP_SECURITY_CONFIG;
  const AMap = await loadAMap();
  if (!mapContainer.value) {
    console.error('地图容器未找到');
    return;
  }
  mapInstance.value = new AMap.Map(mapContainer.value, {
    zoom: 11,
    center: [114.8, 31.1]
  });

   // --- 【核心新增代码】: 初始化并添加地图控件 ---
  const toolBar = new AMap.ToolBar({
    position: {
      top: '120px', // 调整位置，避免与您的搜索框重叠
      right: '40px'
    }
  });
  mapInstance.value.addControl(toolBar);

  const scale = new AMap.Scale();
  mapInstance.value.addControl(scale);

  const mapType = new AMap.MapType({
    defaultType: 0, // 0为路网，1为卫星
    position: {
      top: '120px', // 调整位置
      left: '100px'
    }
  });
  mapInstance.value.addControl(mapType);
  // --- 【新增代码结束】 ---


  initDrawHandlers(AMap);
  mapInstance.value.on('click', handleMapClick);

  // --- 【新增】: 如果用户已登录，则获取他们的足迹列表 ---
  if (authStore.isAuthenticated) {
    await footprintStore.fetchFootprints();
  }

  await performSearch({});
});

// --- 【新增】: 监听登录状态变化，登录后自动获取足迹 ---
watch(() => authStore.isAuthenticated, (isAuth) => {
  if (isAuth) {
    footprintStore.fetchFootprints();
  }
});

const performSearch = async (queryParams, isLoadMore = false) => {
  if (!isLoadMore) {
    clearMarkers();
    propertyStore.resetPropertyState();
  }

    // [核心修正] 修正排序参数的解析方式
  let sortBy = sortConfig.sortBy;
  let order = 'asc'; // 默认升序

  const sortParts = sortConfig.sortBy.split('_');
  if (sortParts.length > 1) {
    order = sortParts.pop(); // 获取最后一部分作为 order
    sortBy = sortParts.join('_'); // 剩下的部分组合成 sortBy (这样 avg_rating 就不会被拆开)
  }

  const finalQueryParams = {
    ...searchParams,
    ...queryParams,
    sort_by: sortBy, // <-- 添加排序字段
    order: order      // <-- 添加排序顺序
  };

  if (!finalQueryParams.name) delete finalQueryParams.name;
  if (!finalQueryParams.district) delete finalQueryParams.district;
  if (!finalQueryParams.sub_district) delete finalQueryParams.sub_district;

  lastQueryParams.value = finalQueryParams;

  // 注意: useApiKeyForSearch 在 property API 中可能没有实现，这里保留前端逻辑
  await propertyStore.fetchProperties(finalQueryParams, useApiKeyForSearch.value, isLoadMore);
};

const resetSearch = () => {
  Object.assign(searchParams, { name: '', district: '', sub_district: '', radius: 5000 });
  lastQueryParams.value = {};
  resetSpatialParams();
  clearCurrentDrawing();
  clearPoiMarkers();
  navigationPanelVisible.value = false; // 【新增】隐藏周边设施的结果面板
  clickModeActive.value = false;
  currentDrawType.value = null;
  if (mapContainer.value) mapContainer.value.style.cursor = 'default';
  performSearch({});
};

const handleExit = async () => {
  await router.push('/login');
};

const initDrawHandlers = (AMap) => {
  const handleDrawStart = (e) => {
    if (!currentDrawType.value || isDrawing.value) return;
    e.originEvent.preventDefault();
    isDrawing.value = true;
    startPoint = e.lnglat;
    mapInstance.value.setStatus({ dragEnable: false, zoomEnable: false });
    mapInstance.value.setDefaultCursor('crosshair');
    currentOverlay = createOverlay(AMap, currentDrawType.value);
    window.addEventListener('mousemove', handleDrawMove);
    window.addEventListener('mouseup', handleDrawEnd);
  };

  const handleDrawMove = (e) => {
    if (!isDrawing.value) return;
    const lnglat = mapInstance.value.containerToLngLat(new AMap.Pixel(e.clientX, e.clientY));
    updateOverlay(currentOverlay, startPoint, lnglat);
  };

  const handleDrawEnd = async (e) => {
    window.removeEventListener('mousemove', handleDrawMove);
    window.removeEventListener('mouseup', handleDrawEnd);
    if (!isDrawing.value) return;
    const overlayThatWasDrawn = currentOverlay;
    isDrawing.value = false;
    currentDrawType.value = null;
    currentOverlay = null;
    startPoint = null;
    mapInstance.value.setStatus({ dragEnable: true, zoomEnable: true });
    mapInstance.value.setDefaultCursor('default');
    try {
      if (overlayThatWasDrawn) {
        await finalizeSearch(overlayThatWasDrawn);
      }
    } catch (error) {
      console.error("搜索错误:", error);
    } finally {
      if (overlayThatWasDrawn && mapInstance.value) {
        mapInstance.value.remove(overlayThatWasDrawn);
      }
    }
  };
  mapInstance.value.on('mousedown', handleDrawStart);
};

const createOverlay = (AMap, type) => {
  const commonStyle = { strokeColor: '#1890ff', strokeWeight: 2, strokeOpacity: 0.8, fillColor: '#1890ff', fillOpacity: 0.15, strokeStyle: 'solid' };
  let overlay = null;
  if (type === 'rectangle') {
    overlay = new AMap.Rectangle({ bounds: new AMap.Bounds(startPoint, startPoint), ...commonStyle });
  }
  if (overlay) overlay.setMap(mapInstance.value);
  return overlay;
};

const updateOverlay = (overlay, start, current) => {
  if (!overlay || !start || !current) return;
  if (overlay instanceof window.AMap.Rectangle) {
    const bounds = new window.AMap.Bounds(start, current);
    overlay.setBounds(bounds);
  }
};

const finalizeSearch = (overlay) => {
  if (!overlay) return;
  const spatialParams = {};
  if (overlay instanceof window.AMap.Rectangle) {
    const bounds = overlay.getBounds();
    spatialParams.sw_lat = bounds.southWest.lat;
    spatialParams.sw_lng = bounds.southWest.lng;
    spatialParams.ne_lat = bounds.northEast.lat;
    spatialParams.ne_lng = bounds.northEast.lng;
  }
  const queryParams = { ...searchParams, ...spatialParams };
  performSearch(queryParams);
};

const enableRectangle = () => {
  if (isDrawing.value) return;
  resetSpatialParams();
  clearCurrentDrawing();
  clickModeActive.value = false;
  currentDrawType.value = 'rectangle';
  if (mapContainer.value) mapContainer.value.style.cursor = 'crosshair';
};

const enablePointSelection = () => {
  if (isDrawing.value) return;
  resetSpatialParams();
  clearCurrentDrawing();
  currentDrawType.value = null;
  clickModeActive.value = true;
  if (mapContainer.value) mapContainer.value.style.cursor = 'crosshair';
};

const clearCurrentDrawing = () => {
  if (currentOverlay && mapInstance.value) {
    mapInstance.value.remove(currentOverlay);
    currentOverlay = null;
  }
  if (currentCircle.value && mapInstance.value) {
    mapInstance.value.remove(currentCircle.value);
    currentCircle.value = null;
  }
};

const handleSearch = async (searchType = 'text') => {
  if (searchType === 'text') {
    resetSpatialParams();
    clearCurrentDrawing();
  }
  await performSearch({});
};

const resetSpatialParams = () => {
  clearCurrentDrawing();
};

const handleMapClick = async (e) => {
  if (!clickModeActive.value || isDrawing.value) return;
  clickModeActive.value = false;
  if (mapContainer.value) mapContainer.value.style.cursor = 'default';
  try {
    const { value: radiusKm } = await ElMessageBox.prompt(
      '请输入搜索半径（公里）', '半径设置',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^\d*\.?\d+$/,
        inputErrorMessage: '请输入有效数字'
      }
    );
    const radiusMeters = parseFloat(radiusKm) * 1000;
    if (radiusMeters > 0) {
      resetSpatialParams();
      drawSearchCircle(e.lnglat, radiusMeters);
      const queryParams = {
        center_lat: e.lnglat.lat,
        center_lng: e.lnglat.lng,
        radius: radiusMeters
      };
      await performSearch(queryParams);
    }
  } catch (action) {
    if (action === 'cancel') {
      ElMessage({ type: 'info', message: '已取消点选搜索' });
    }
  } finally {
    clickModeActive.value = false;
    if (mapContainer.value) mapContainer.value.style.cursor = 'default';
  }
};

const clearMarkers = () => {
  if (mapInstance.value && markers.value.length > 0) {
    mapInstance.value.remove(markers.value);
    markers.value = [];
  }
};

const clearPoiMarkers = () => {
  if (mapInstance.value && poiMarkers.value.length > 0) {
    mapInstance.value.remove(poiMarkers.value);
    poiMarkers.value = [];
  }
};


const drawSearchCircle = (center, radius) => {
  if (currentCircle.value && mapInstance.value) {
    mapInstance.value.remove(currentCircle.value);
  }
  const AMap = window.AMap;
  currentCircle.value = new AMap.Circle({
    center: [center.lng, center.lat],
    radius: radius,
    strokeColor: '#FF33FF',
    fillColor: '#FF33FF',
    fillOpacity: 0.2,
    strokeWeight: 2,
    map: mapInstance.value
  });
   mapInstance.value.setFitView([currentCircle.value]);
};

function loadAMap() {
  return new Promise((resolve, reject) => {
    if (window.AMap) return resolve(window.AMap);
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'https://webapi.amap.com/maps?v=2.0&key=f275bdf35f914d36658f2ab2c7c0feb4&plugin=AMap.MouseTool,AMap.Rectangle,AMap.Circle,AMap.ToolBar,AMap.Scale,AMap.MapType,AMap.Driving,AMap.Geolocation,AMap.PlaceSearch,AMap.Geocoder';
    script.onload = () => {
      console.log('AMap script loaded successfully');
      resolve(window.AMap);
    };
    script.onerror = () => reject(new Error('Failed to load AMap script'));
    document.head.appendChild(script);
  });
}

// --- 【修复问题1】修改 loadMoreProperties 以使用保存的查询参数 ---
const loadMoreProperties = async () => {
  console.log('loadMoreProperties called:', {
    hasMore: propertyStore.hasMore,
    loading: propertyStore.loading,
    lastQueryParams: lastQueryParams.value,
    currentPage: propertyStore.currentPage
  });
  if (!propertyStore.hasMore || propertyStore.loading) return;
  // 使用 lastQueryParams.value 来加载下一页，而不是空的 {}
  await performSearch(lastQueryParams.value, true);
};
</script>

<style scoped>
/* 样式部分无需修改，予以保留 */
.map-container-wrapper {
  position: relative;
  width: 100%;
  height: calc(100vh - 60px - 40px);
}
.navigation-panel {
  position: absolute;
  top: 130px; /* 调整位置，避免遮挡其他控件 */
  right: 10px;
  width: 280px;
  height: 70%;
  z-index: 1000;
  background-color: white;
  overflow-y: auto;
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
  border-radius: 4px;
  padding: 10px;
}
.map-view-core {
  width: 100%;
  height: 100%;
}
.map-controls {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 990;
  background: rgba(255, 255, 255, 0.9);
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
}

.button-group-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.map-controls .el-input, .map-controls .el-input-number {
  width: 150px;
}

.map-feedback-alert {
  position: absolute;
  top: 70px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1001;
  min-width: 300px;
  text-align: center;
}
.bottom-right-button {
  position: fixed;
  right: 40px;
  bottom: 40px;
  z-index: 10;
}
/* 确保自定义弹窗样式被应用 */
.custom-info-window {
  padding: 10px;
  line-height: 1.6;
}
.custom-info-window h3 {
  margin: 0 0 8px;
  color: #1890ff;
}
.custom-info-window table {
  width: 100%;
  font-size: 12px;
}
.custom-info-window td {
  padding: 4px;
}
.custom-info-window td:first-child {
  color: #666;
}
.custom-info-window a {
  color: #409EFF;
  text-decoration: none;
}
</style>